package com.yu.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.net.UnknownHostException;

/**
 * @Description: TODO
 * @Author : yu
 * Date : 4/12/2020 11:51 PM
 */
@Configuration
public class RedisConfig {


        @Bean
        @SuppressWarnings("all")
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            //为了开发方便，我们使用<String, Object>
            RedisTemplate<String, Object> template = new RedisTemplate<>();



            //配置具体的json序列化方式
            Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
            //设置连接工厂
            template.setConnectionFactory(redisConnectionFactory);
            //这个应该是给序列化器的一个序列化格式的一些设置什么的。
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            jackson2JsonRedisSerializer.setObjectMapper(om);
            template.setKeySerializer(jackson2JsonRedisSerializer);


            //string序列化
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            //key采用String的序列化方式
            template.setKeySerializer(stringRedisSerializer);
            //hash的key也使用string的序列化方式
            template.setHashKeySerializer(stringRedisSerializer);
            //hash的value使用jackson序列化
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            //value使用json序列化
            template.setValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();

            return template;
        }
}
